﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Queue;
using System.Collections.Specialized;
using System.Threading;
using System.Globalization;
using System.Threading.Tasks;

namespace CloudTrace
{
    public class QueueTraceListener : CloudTraceListener
    {
        private CloudQueue queue;

        #region ctor
        public QueueTraceListener(string initializeData)
            : base(initializeData)
        {
        }

        #endregion

        #region Queue Message Transfer
        protected override void SaveMessage(LogMessage logMessage)
        {
            if (null == this.queue)
                this.InitializeService();

            CloudQueueMessage msg;

            if (!plainTextMessages)
            {
                logMessage.SetProperties();
                byte[] buffer = LogMessage.Serialize(logMessage);
                msg = new CloudQueueMessage(buffer);
            }
            else
            {
                msg = new CloudQueueMessage(logMessage.ToString());
            }
            if (this.async)
            {
                Task task = Task.Factory.FromAsync(queue.BeginAddMessage, queue.EndAddMessage, msg, null);
                this.tasks.Add(task);
                task.ContinueWith(t => tasks.Remove(t));
            }
            else
            {
                queue.AddMessage(msg);
            }
        }
        #endregion

        #region private helpers
        protected override void InitializeService()
        {
            base.Initialize();

            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
            this.queue = queueClient.GetQueueReference((Attributes[SupportedAttributes.queueName.ToString()]
                ?? settings[SupportedAttributes.queueName.ToString()] ?? "QueueTraceListener").ToLowerInvariant());
            this.queue.CreateIfNotExists();
        }
        #endregion

    }
}
